import api from '../../api/api'
import Toast from '@vant/weapp/toast/toast'
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    detailData: {},
    desc: '',
    active: 0,
    countNum: 1,
    isLike: false,
    pid: null
  },
  async getDetailData(pid) {
    const res = await api.getDetail({ pid })
    const allRules = []
    const roulesTitle = ['cream', 'milk', 'sugar', 'tem']
    roulesTitle.forEach((item) => {
      // 过滤空的规格
      if (!res.data.result[0][item]) {
        return
      }
      // 构造一个规格对象
      const diyRules = {
        title: res.data.result[0][`${item}_desc`],
        activeIndex: 0,
        rules: []
      }
      // 处理子规格（无糖，三分糖，冷，热等）数据
      const subRules = res.data.result[0][item].split(/\//)
      subRules.forEach((item) => {
        diyRules.rules.push({ title: item })
      })
      allRules.push(diyRules)
    })
    res.data.result[0].newRules = allRules
    this.setData({
      detailData: res.data.result[0],
      desc: res.data.result[0].desc.split('\n')
    })
    console.log('商品详情', res)
  },
  addClass(e) {
    let index = e.currentTarget.dataset.index
    let i = e.currentTarget.dataset.i
    this.setData({
      ['detailData.newRules[' + index + '].activeIndex']: i
    })
  },
  imageView(e) {
    let img = e.currentTarget.dataset.img
    wx.previewImage({
      current: img,
      urls: [img]
    })
  },
  async addShopCart(e) {
    if (wx.getStorageSync('token')) {
      let pid = e.currentTarget.dataset.pid
      const allRules = []
      this.data.detailData.newRules.forEach((item) => {
        allRules.push(item.rules[item.activeIndex].title)
      })
      const res = await api.addCart({
        pid,
        count: this.data.countNum,
        rule: allRules.join('/'),
        tokenString: wx.getStorageSync('token')
      })
      if (res.data.code == 3000) {
        Toast.success(res.data.msg)
      }
    } else {
      app.checkLogin()
    }

  },
  toCart() {
    wx.switchTab({
      url: '/pages/shop/shop',
    })
  },
  changeCount(e) {
    this.setData({
      countNum: e.detail
    })
  },
  async collect(e) {
    if (!wx.getStorageSync('token')) {
      app.checkLogin()
      return
    }
    const tokenString = wx.getStorageSync('token')
    let pid = e.currentTarget.dataset.pid
    const res = this.data.isLike ? await api.noLike({ tokenString, pid }) : await api.like({ tokenString, pid })
    // 如果用户未登录
    if (res.data.code == 700) {
      app.checkLogin()
    }
    // 收藏成功
    if (res.data.code == 800) {
      console.log('收藏', res);
      Toast(res.data.msg)
      this.setData({
        isLike: true
      })
    }
    // 取消收藏
    if (res.data.code == 900) {
      console.log('取消收藏', res);
      Toast(res.data.msg)
      this.setData({
        isLike: false
      })
    }
  },
  async findLikeData(pid) {
    const res = await api.findLike({ tokenString: wx.getStorageSync('token'), pid })
    if (res.data.code == 1000) {
      console.log('查询商品是否收藏', res);
      if (res.data.result.length != 0) {
        this.setData({
          isLike: true
          // isLike: false
        })
      } else {
        this.setData({
          isLike: false
          // isLike: true
        })
      }
    } else {
      app.checkLogin()
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  async onLoad(options) {
    this.setData({
      pid: options.pid
    })
    this.findLikeData(this.data.pid)
    this.getDetailData(this.data.pid)
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.findLikeData(this.data.pid)
    this.getDetailData(this.data.pid)

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})